<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        {{ this.isEdit ? '试题修改' : '试题录入' }}
      </el-card>
      <el-card>
        <el-form ref="formData" :model="formData" :rules="rules" label-width="120px" size="medium">
          <!-- 第一行：学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="formData.subjectID" @change="subject_select" placeholder="请选择">
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 第二行：目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="formData.catalogID" placeholder="请选择">
              <el-option
                v-for="item in catalogueList"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 第三行：企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="formData.enterpriseID" placeholder="请选择">
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 第四行：城市 -->
          <el-form-item label="城市：" prop="city">
            <!-- 市 -->
            <el-select
              class="citySelect"
              v-model="formData.province"
              @change="city_select"
              placeholder="请选择">
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :label="item"
                :value="item"
                >
              </el-option>
            </el-select>
            <!-- 区 -->
            <el-select
              class="citySelect"
              v-model="formData.city"
              collapse-tags
              style="margin-left: 20px;"
              placeholder="请选择">
              <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 第五行：方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="formData.direction" placeholder="请选择">
              <el-option
                v-for="(item, index) in directionList"
                :key="index"
                :label="item"
                :value="item"
                >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 第六行：题型 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="formData.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 第七行：难度 -->
          <el-form-item label="难度：" prop="questionType">
            <el-radio-group v-model="formData.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 第八行：题干 -->
          <el-form-item label="题干：" prop="question">
            <quillEditor
              v-model="formData.question"
              :options="editorOption"
              @blur="quillBlur"
              />
          </el-form-item>
          <!-- 第九行：选项 -->
          <el-form-item label="选项：" v-if="radioOrCheckbox !== '3'">
            <el-form-item
              v-model="formData.options"
              v-for="(obj, index) in this.formData.options"
              :key="index"
              >
              <el-row>
                <el-col :span="1">
                  <el-checkbox
                    class="checkbox"
                    v-if="radioOrCheckbox === '2'"
                    v-model="checkList"
                    :label="obj.code"
                    >
                    {{ obj.code }}:
                  </el-checkbox>
                  <el-radio
                    v-if="radioOrCheckbox === '1'"
                    v-model="radio"
                    :label="obj.code"
                    >
                    {{ obj.code }}:
                  </el-radio>
                </el-col>
                <el-col :span="8.5">
                  <el-input
                    class="smallInput"
                    v-model="obj.title"
                    placeholder=""
                    >
                  </el-input>
                </el-col>
                <el-col :span="14.5">
                  <el-upload
                    action="#"
                    :show-file-list="false"
                  >
                    <div class="avatar">
                      <img v-if="obj.img" :src="obj.img" class="img" />
                      <span v-else @click="uploading(index)">上传图片</span>
                    </div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button :disabled="isDisabled" type="danger" @click="addOptionAddAnswer" size="mini">+增加选项与答案</el-button>
          </el-form-item>
          <!-- 第十行：解析视频 -->
          <el-form-item label="解析视频：">
            <el-input
              v-model="formData.videoURL"
              class="video"
              >
            </el-input>
          </el-form-item>
          <!-- 第十一行：答案解析 -->
          <el-form-item label="答案解析：" prop="question">
            <quillEditor
              v-model="formData.answer"
              :options="editorOption"
              @blur="quillBlur"
              />
          </el-form-item>
          <!-- 第十二行：题目备注 -->
          <el-form-item label="题目备注：">
            <el-input v-model="formData.remarks" type="textarea"></el-input>
          </el-form-item>
          <!-- 第十三行：试题标签 -->
          <el-form-item label="试题标签：">
            <el-select
              v-model="formData.tags"
              placeholder="请选择"
              :multiple="true"
              filterable
              allow-create
              default-first-option
              >
              <el-option
                v-for="(item, index) in questionLabelList"
                :key="index"
                :label="item.tagName"
                :value="item.tagName"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 第十四行：提交按钮 -->
          <el-form-item>
            <el-button :type="this.isEdit ? 'success' : 'primary'" @click="onSubmit">
              {{ this.isEdit ? '确认修改' : '确认提交' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入题型和难度
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js'
// 引入学科列表方法
import { list } from '@/api/hmmm/subjects.js'
// 引入企业列表方法
import { list as enterpriseList } from '@/api/hmmm/companys.js'
// 引入城市及地区
import { provinces, citys } from '@/api/hmmm/citys.js'
// 引入获取目录
import { list as catalogueList } from '@/api/hmmm/directorys.js'
// 引入试题标签
import { list as questionLabelList } from '@/api/hmmm/tags.js'
// 引入基础题库
import { add, detail, update } from '@/api/hmmm/questions.js'
// 引入富文本
import { quillEditor } from 'vue-quill-editor'
// 富文本样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  components: { quillEditor },
  data () {
    return {
      // 富文本配置项
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'bullet' }, { list: 'ordered' }],
            ['blockquote', 'code-block', 'image', 'link']
          ]
        },
        placeholder: ''
      },

      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 区域
        direction: '', // 方向
        questionType: '1', // 题型及默认选中
        difficulty: '1', // 难度及默认选中
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        // 选项
        options: [
          {
            code: 'A', // 代码
            title: '', // 标题
            img: '', // 图片Url
            isRight: 0 // 是否正确答案
          },
          {
            code: 'B', // 代码
            title: '', // 标题
            img: '', // 图片Url
            isRight: 0 // 是否正确答案
          },
          {
            code: 'C', // 代码
            title: '', // 标题
            img: '', // 图片Url
            isRight: 0 // 是否正确答案
          },
          {
            code: 'D', // 代码
            title: '', // 标题
            img: '', // 图片Url
            isRight: 0 // 是否正确答案
          }
        ]
      },
      subjectList: [], // 学科列表
      catalogueList: [], // 目录列表
      enterpriseList: [], // 企业列表
      provinceList: [], // 城市列表
      cityList: [], // 区域列表
      directionList: [], // 方向列表
      questionTypeList: [], // 题型列表
      difficultyList: [], // 难度列表
      optionList: [], // 选项列表
      questionLabelList: [], // 试题标签列表
      radioOrCheckbox: '1', // 单选或多选状态
      radio: '', // 单选信息
      checkList: [], // 多选信息
      isDisabled: true, // 按钮状态
      isEdit: this.$route.query.id, // 通过编辑时传递来的ID确认是否是编辑状态
      subjectIDs: '', // 保存学科ID
      catalogIDs: '', // 保存目录ID
      index: '', // 点击上传图片对应的ID
      // 校验规则
      rules: {
        // 学科
        subjectID: [
          {
            required: true, message: '请选择学科', trigger: 'change'
          }
        ],
        // 目录
        catalogID: [
          {
            required: true, message: '请选择目录', trigger: 'change'
          }
        ],
        // 企业
        enterpriseID: [
          {
            required: true, message: '请选择企业', trigger: 'change'
          }
        ],
        // 城市
        city: [
          {
            required: true, message: '请选择地区', trigger: 'change'
          }
        ],
        // 方向
        direction: [
          {
            required: true, message: '请选择方向', trigger: 'change'
          }
        ],
        // 题型、难度
        questionType: [
          {
            required: true, trigger: 'change'
          }
        ],
        // 题干、答案
        question: [
          {
            required: true, message: '请输入题干', trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    // 获取题型列表
    this.questionTypeList = questionType
    // 获取难度列表
    this.difficultyList = difficulty
    // 获取方向列表
    this.directionList = direction
    // 获取学科列表
    this.getSubjectList()
    // 获取城市列表
    this.getAllCity()
    // 获取企业列表
    this.getCompanysList()
  },
  methods: {
    // 增加选项与答案
    addOptionAddAnswer () {
      const i = this.formData.options.length - 1 // 获取数组内最后一个对象的下标
      const en = this.formData.options[i].code // 取出最后一个对象的字母
      const shu = en.charCodeAt() // 查询这个字母在阿斯克码值的序号
      const obj = {
        code: String.fromCharCode(shu + 1), // 加一变为字符串传回去
        title: '',
        img: '',
        isRight: 0
      }
      this.formData.options.push(obj)
    },

    // 获取学科列表
    async getSubjectList () {
      // 如果是编辑页面, 根据传递来的 ID 做表单回显
      if (this.isEdit) {
        const res = await detail({ id: this.isEdit })

        // 通过sort方法进行排序, 比较他们的code值
        const arr = res.data.options.sort(function (a, b) {
          return a.code.charCodeAt() - b.code.charCodeAt()
        })
        this.formData.options = arr

        this.subjectIDs = res.data.subjectID
        this.catalogIDs = res.data.catalogID
        this.formData = res.data
        this.formData.subjectID = res.data.subjectName
        this.formData.catalogID = res.data.directoryName
        // 判断标签是否为空
        if (res.data.tags === '') {
          this.formData.tags = []
        } else {
          this.formData.tags = res.data.tags.split(',')
        }
        this.city_select()
        this.subject_select()
        // 单选状态
        if (res.data.questionType === '1') {
          res.data.options.forEach((item) => {
            if (item.isRight === 1) {
              this.radio = item.code
            }
          })
        } else {
          // 多选状态
          res.data.options.forEach((item) => {
            if (item.isRight === 1) {
              this.checkList.push(item.code)
            }
          })
        }
        const ress = await list({ page: 1, pagesize: 40 })
        this.subjectList = ress.data.items
      } else {
        const res = await list(this.formData.subject)
        this.subjectList = res.data.items
      }
    },

    // 获取到学科后获取目录和试题标签
    async subject_select () {
      // 获取目录
      const res = await catalogueList()
      this.catalogueList = res.data.items
      // 获取试题标签
      const res1 = await questionLabelList()
      this.questionLabelList = res1.data.items
    },

    // 获取企业
    async getCompanysList () {
      const res = await enterpriseList()
      this.enterpriseList = res.data.items
    },

    // 获取所有城市
    getAllCity () {
      const res = provinces()
      this.provinceList = res
    },

    // 获取到城市后获取区域
    city_select () {
      const res = citys(this.formData.province)
      this.cityList = res // 区域列表
    },

    // 表单提交兜底验证
    onSubmit () {
      this.$refs.formData.validate(async valid => {
        if (valid) {
          this.formData.tags = this.formData.tags.join()
          this.formData.questionType = String(this.formData.questionType)
          this.formData.difficulty = String(this.formData.difficulty)
          if (this.isEdit) {
            this.formData = { ...this.formData, id: +this.isEdit }
            if (typeof this.formData.subjectID === 'string') {
              this.formData.subjectID = this.subjectIDs
            }
            if (typeof this.formData.catalogID === 'string') {
              this.formData.catalogID = this.catalogIDs
            }
            const res = await update(this.formData)
            // 跳转到基础题库
            this.$router.push('list')
            // 成功提示
            this.$message.success('修改试题成功')
          } else {
            const res = await add(this.formData)
            // 跳转到基础题库
            this.$router.push('list')
            // 成功提示
            this.$message.success('提交试题成功')
          }
          // 重置默认项
          this.$nextTick(() => {
            this.formData.questionType = '1'
            this.formData.difficulty = '1'
          })
        } else {
          return false
        }
      })
    },

    // 点击上传图片
    uploading (i) {
      this.index = i
    },

    // 富文本失去焦点自动验证
    quillBlur () {
      this.$refs.formData.validateField('question')
    }
  },
  watch: {
    // 侦听题型
    'formData.questionType': function (newVal, oldVal) {
      switch (newVal) {
        case '1':
          this.radioOrCheckbox = '1'
          this.isDisabled = true
          this.checkList = []
          break
        case '2':
          this.radioOrCheckbox = '2'
          this.isDisabled = false
          this.radio = ''
          break
        case '3':
          this.radioOrCheckbox = '3'
          this.radio = ''
          this.checkList = []
      }
    },
    // 侦听单选框变化
    radio: function (newValue, oldValue) {
      this.formData.options.forEach((item) => {
        item.isRight = 0
        if (item.code === newValue) {
          item.isRight = 1
        }
      })
    },
    // 侦听复选框变化
    checkList: function (newValue, oldValue) {
      this.formData.options.forEach((item) => {
        item.isRight = 0
        this.checkList.forEach((val) => {
          if (item.code === val) {
            item.isRight = 1
          }
        })
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-input.el-input--medium.el-input--suffix {
    width: 400px;
}

::v-deep textarea.el-textarea__inner {
    width: 400px;
    height: 100px;
}

.el-row {
    height: 70px;
}

button.el-button.el-button--danger.el-button--mini {
    height: 35px;
}

::v-deep .smallInput input.el-input__inner {
  margin-top: 10px;
  width: 250px;
}

::v-deep .citySelect .el-input.el-input--medium.el-input--suffix {
  width: 190px;
}

::v-deep .ql-editor{
min-height:200px;
}

.avatar {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}

.img {
  width: 120px;
  height: 80px;
}

.el-col.el-col-1 {
  padding-top: 10px;
}

.el-select {
    width: 400px;
}

::v-deep .video input.el-input__inner {
  width: 400px;
}

.el-select.citySelect.el-select--medium {
    width: 190px;
}
</style>
